﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using JPSOFTWARE.BON.DAL;
using System.Web.Routing;

namespace JPSoftwareMVC.Filtro
{
    public class RegraAcesso : AuthorizeAttribute
    {
        readonly dbBONDataContext _dbBon;

        public RegraAcesso()
        {
            _dbBon = null;
            _dbBon = new dbBONDataContext(BaseDAL.StringConexao());
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.Request.IsAuthenticated)
            {
                return false;
            }

            var loggedInUser = UsuarioPorEmail(httpContext.User.Identity.Name);
            string[] userRoles = regraPorUsuario(loggedInUser.COD_USUARIO);

            foreach (string definedRole in this.Roles.Split(','))
            {
                foreach (string role in userRoles)
                {
                    if (definedRole.Trim() == role)
                        return true;
                }
            }

            return false;
        }
        
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //StringBuilder msg = new StringBuilder();
            //string imagem = "/Content/bootstrap/img/acessoRestrito.jpg";

            //msg.Append("<center>");
            //msg.Append("<img src='" + imagem + "' border='0' style='margin-top:50px;' />");
            //msg.Append("<br/>");
            //msg.Append("<a href='javascript:history.go(-1)'>Ok, voltar ao Bebida Social</a>");
            //msg.Append("</center>");            

            //string minhaMsg = msg.ToString();

            //filterContext.Result = new ErrorActionResult { ErrorMessage = minhaMsg };

            var routeValues = new RouteValueDictionary();
            routeValues["controller"] = "Login";
            routeValues["action"] = "LogOn";
            routeValues["area"] = String.Empty;
            filterContext.Result = new RedirectToRouteResult(routeValues);
            
        }
         

        public class ErrorActionResult : ActionResult
        {
            public string ErrorMessage { get; set; }

            public override void ExecuteResult(ControllerContext context)
            {
                context.HttpContext.Response.Write(this.ErrorMessage);
            }
        }

        public TBL_USUARIO UsuarioPorEmail(string email)
        {
            //dbBONDataContext dbBON = new dbBONDataContext();

            TBL_USUARIO usuario = new TBL_USUARIO();

            usuario = _dbBon.TBL_USUARIOs.FirstOrDefault(x => x.DS_EMAIL == email);

            return usuario;
        }

        public string[] regraPorUsuario(int idUsuario)
        {            
            var usuario = _dbBon.TBL_USUARIOs.SingleOrDefault(u => u.COD_USUARIO == idUsuario);

            var usersInRoles = (from tu in _dbBon.TBL_TIPO_USUARIOs
                                join u in _dbBon.TBL_USUARIOs on tu.COD_TIPO_USUARIO equals u.COD_TIPO_USUARIO
                                where u.COD_USUARIO == idUsuario
                                select tu).ToList();

            if (usuario != null)
                return usersInRoles.Select(y => y.NM_TIPO_USUARIO).ToArray();

            return new string[0];
        }
    }
}